/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.common;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.util.Log;

import com.worklight.androidgap.WLAndroidUtils;

/**
 * @author Ishai Borovoy
 * 
 * WLPreferences - general Worklight Preference Activity
 * This Activity class let the developer/tester to change settings.
 * The state of the settings saved in Worklight SharedPreferences.
 */
public class WLPreferences extends PreferenceActivity {
	//prefs keys
	private static final String EDIT_WL_SERVER_URL_PREF = "editWLServerURLPref";
	private static final String MODIFY_WL_SERVER_URL_PREF = "resetWLServerURLPref";
	private static final String SHOULD_MODIFY_URL_PREF = "shouldModifyUrlPref";
	private static final String LAST_SETTINGS_URL_STATE_PREF = "lastSettingsUrlStatePref";
	
	private static final String NEW_LINE = "\n";
	private static final String WL_CLIENT_PROPS_NAME = "wlclient.properties";
	private static final String WL_SERVER_URL = "WLServerURL";
	private static final String WL_SERVER_HOST = "wlServerHost";
	private static final String WL_SERVER_PROTOCOL = "wlServerProtocol";
	private static final String WL_SERVER_PORT = "wlServerPort";
	
	
	
	
	private Properties wlProperties = null;
	private String serverURL = null;
	
	@SuppressWarnings("rawtypes")
	// R$string class with reflection 
	private Class rStringClass = null;
	
	private EditTextPreference serverURLEditTextPreference = null;
	private CheckBoxPreference modifyServerURLCheckBoxPreference = null;
	
	// save the url from last time to know if changed
	private String beforeChangeUrlValue = null;
			
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		final String networkSettingsTitleWLServerUrl = getResourceString("networkSettingsTitleWLServerUrl");
		final String OKTitleWLServerUrl = getResourceString("OKTitleWLServerUrl");
		final String titleInvalidWLServerUrl = getResourceString("titleInvalidWLServerUrl");
		final String errorInvalidWLServerUrl = getResourceString("errorInvalidWLServerUrl");
		
		PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
		final PreferenceCategory networkSettingsCategory = new PreferenceCategory(this);
		networkSettingsCategory.setTitle(networkSettingsTitleWLServerUrl);
		root.addPreference(networkSettingsCategory);
		// save the url from before to know if need to reload
		beforeChangeUrlValue = WLAndroidUtils.readWLPref(WLPreferences.this.getApplicationContext(), WL_SERVER_URL);
		// create the modify server checkbox
		createModifyServerCheckbox();
		// create the server text field
		createServerURLTextField();
		
		networkSettingsCategory.addPreference(modifyServerURLCheckBoxPreference);
		networkSettingsCategory.addPreference(serverURLEditTextPreference);
		setPreferenceScreen(root);
		
		modifyServerURLCheckBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				Boolean allowModifyURL = (Boolean)newValue;
				if (allowModifyURL) {
					WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), SHOULD_MODIFY_URL_PREF, "true");
					WLPreferences.this.serverURLEditTextPreference.setEnabled(true);
					serverURL = WLPreferences.this.serverURLEditTextPreference.getText();
					WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), WL_SERVER_URL, serverURL);
				} else {
					WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), SHOULD_MODIFY_URL_PREF, "false");
					serverURL = getDefaultServerURL();
					WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), WL_SERVER_URL, serverURL);
					WLPreferences.this.serverURLEditTextPreference.setEnabled(false);
				}
				return true;
			}
		});
		
		serverURLEditTextPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@SuppressWarnings("unused")
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {	
				serverURL = (String)newValue;
				// validate url
				try {
					new URL (serverURL);
				} catch (MalformedURLException e) {
					new AlertDialog.Builder(WLPreferences.this)
					.setTitle(titleInvalidWLServerUrl)
					.setMessage(serverURL + " " + errorInvalidWLServerUrl)
					.setNeutralButton(OKTitleWLServerUrl, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int which) {
							//Nothing to do on click, just closing the dialog
						}
					}).show();
				     return false;
				}
				WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), WL_SERVER_URL, serverURL);
				WLAndroidUtils.writeWLPref(WLPreferences.this.getApplicationContext(), LAST_SETTINGS_URL_STATE_PREF, serverURL);
				WLPreferences.this.setServerURLFieldSummary();
				return true;
			}
		});
	}

	//Create The URL TextField
	private void createServerURLTextField() {
		String summaryWLServerUrl = getResourceString("summaryWLServerUrl");
		String titleWLServerUrl = getResourceString("titleWLServerUrl");
		serverURLEditTextPreference = new EditTextPreference (this);
		this.serverURL =  WLAndroidUtils.readWLPref(WLPreferences.this.getApplicationContext(), WL_SERVER_URL);
		
		if (this.serverURL == null || this.serverURL.trim().equals("")) {
			this.serverURL = getDefaultServerURL();
		}
		
		serverURLEditTextPreference.setTitle(titleWLServerUrl);
		serverURLEditTextPreference.setKey(EDIT_WL_SERVER_URL_PREF);
		serverURLEditTextPreference.setDefaultValue(serverURL);
		String lastSavedUrl =  WLAndroidUtils.readWLPref(WLPreferences.this.getApplicationContext(), LAST_SETTINGS_URL_STATE_PREF);
		serverURLEditTextPreference.setSummary(lastSavedUrl == null ? summaryWLServerUrl : lastSavedUrl + NEW_LINE + summaryWLServerUrl);
		String modifyCheckState =  WLAndroidUtils.readWLPref(WLPreferences.this.getApplicationContext(), SHOULD_MODIFY_URL_PREF);
		serverURLEditTextPreference.setEnabled(modifyCheckState == null || !Boolean.valueOf(modifyCheckState) ? false : true);
		serverURLEditTextPreference.setPersistent(true);
	}

	//Create the modif CheckBox
	private void createModifyServerCheckbox() {
		modifyServerURLCheckBoxPreference = new CheckBoxPreference(this);
		modifyServerURLCheckBoxPreference.setTitle(getResourceString("serverAddress"));
		modifyServerURLCheckBoxPreference.setSummary(getResourceString("changeServerAddress"));
		modifyServerURLCheckBoxPreference.setKey(MODIFY_WL_SERVER_URL_PREF);
		modifyServerURLCheckBoxPreference.setPersistent(true);
	}
	
	private void setServerURLFieldSummary() {
		String summary = (String) serverURLEditTextPreference.getSummary();
		if (summary.contains(NEW_LINE)) {
			summary = summary.substring(summary.lastIndexOf(NEW_LINE) + 1, summary.length());
		}
		serverURLEditTextPreference.setSummary(serverURL + NEW_LINE + summary);
	}
	
	private String getResourceString (String recourceName) {
		try {
			if (rStringClass == null) {
				rStringClass = Class.forName(getApplication().getPackageName() + ".R$string");
			}
			return getResources().getString((Integer) rStringClass.getDeclaredField(recourceName).get(null));
		} catch (Exception e) {
			Log.e(getPackageName(), e.getMessage(), e);
			finish();
			return "";
		}
	}

	private String getDefaultServerURL() {
		if (wlProperties == null){
			try {
				this.wlProperties = new Properties();
				this.wlProperties.load(this.getAssets().open(WL_CLIENT_PROPS_NAME));
			} catch (IOException e) {
				throw new RuntimeException ("Can't load " + WL_CLIENT_PROPS_NAME + " file");
			}
		}
		return String.format("%s://%s%s", 
				wlProperties.get(WL_SERVER_PROTOCOL), 
				wlProperties.get(WL_SERVER_HOST), 
				wlProperties.get(WL_SERVER_PORT) == null ? "" : ":" + wlProperties.get(WL_SERVER_PORT));
	}
		
	private boolean isUrlChanged() {
		return beforeChangeUrlValue == null || !beforeChangeUrlValue.equals(serverURL);
	}
	
	@Override
	public void onBackPressed() {
		Intent settings = new Intent ();
		settings.putExtra("isServerURLChanged", isUrlChanged());
		settings.putExtra("serverURL", serverURL);
		setResult(RESULT_OK, settings); 
		super.onBackPressed();
	}
}